package com.XDApp.xdbase.activitys;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.XDApp.xdbase.view.DateWidgetDayCell;
import com.XDApp.xdbase.view.DateWidgetDayHeader;
import com.XDApp.xdbase.view.DayStyle;
import com.XDApp.xdbase.xinsilu.R;

public class CalendarActivity extends Activity {

	private final ArrayList<DateWidgetDayCell> days = new ArrayList<DateWidgetDayCell>();
	private Calendar calStartDate = Calendar.getInstance();
	private final Calendar nextDate = Calendar.getInstance();
	private final Calendar nnextDate = Calendar.getInstance();
	private final Calendar calToday = Calendar.getInstance();
	private final Calendar calCalendar = Calendar.getInstance();
	private final Calendar calSelected = Calendar.getInstance();

	LinearLayout layContent = null;
	// Button btnToday = null;

	private int iFirstDayOfWeek = Calendar.MONDAY;
	private int iMonthViewCurrentMonth = 0;
	private int iMonthViewCurrentYear = 0;
	public static final int SELECT_DATE_REQUEST = 111;
	private int iDayCellSize = 38;
	private int iDayHeaderHeight = 24;
	private int iTotalWidth = (iDayCellSize * 7);
	// private TextView tv;
	private String strDate = "";
	// , monthTextView, yearTextView;
	private TextView tvYear, tvMonth;
	private Button btnPreMonth, btnNextMonth;
	private int mYear;
	private int mMonth;
	private int mDay;
	// private int type;

	private LinearLayout ll;
	// 标题控件
	private ImageView back;
	private TextView title;
	/**
	 * 屏幕的宽度、高度、密度
	 */
	protected int mScreenWidth;
	protected int mScreenHeight;
	protected float mDensity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calendar);

		tvYear = (TextView) findViewById(R.id.tv_year);
		tvMonth = (TextView) findViewById(R.id.tv_month);
		btnPreMonth = (Button) findViewById(R.id.btn_premonth);
		btnNextMonth = (Button) findViewById(R.id.btn_nextmonth);
		// 标题控件
		back = (ImageView) findViewById(R.id.title_back);
		title = (TextView) findViewById(R.id.title_text);
		title.setText("选择时间");
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		mScreenWidth = metric.widthPixels;
		mScreenHeight = metric.heightPixels;

		iDayCellSize = (mScreenWidth - 48) / 7;
		iTotalWidth = (iDayCellSize * 7);
		iDayHeaderHeight = iDayCellSize * 2 / 3;

		ll = (LinearLayout) findViewById(R.id.ll);

		Bundle bundle = this.getIntent().getExtras();
//		type = bundle.getInt("type");

		iFirstDayOfWeek = Calendar.MONDAY;
		mYear = calSelected.get(Calendar.YEAR);
		mMonth = calSelected.get(Calendar.MONTH);
		mDay = calSelected.get(Calendar.DAY_OF_MONTH);

		ll.addView(generateContentView());

		ll.invalidate();

		calStartDate = getCalendarStartDate();

		nextDate.setTime(new Date()); // 当天
		nextDate.add(Calendar.DAY_OF_YEAR, 1); // 下一天

		nnextDate.setTime(new Date()); // 当天
		nnextDate.add(Calendar.DAY_OF_YEAR, 2); // 下一天

		DateWidgetDayCell daySelected = updateCalendar();
		updateControlsState();

		if (daySelected != null)
			daySelected.requestFocus();

		btnNextMonth.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setNextMonthViewItem();
			}
		});

		btnPreMonth.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setPrevMonthViewItem();
			}
		});

		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	@Override
	public void onStart() {
		super.onStart();
	}

	private LinearLayout createLayout(int iOrientation) {
		LinearLayout lay = new LinearLayout(this);
		lay.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
		lay.setOrientation(iOrientation);
		return lay;
	}

	private Button createButton(String sText, int iWidth, int iHeight) {
		Button btn = new Button(this);
		btn.setText(sText);
		btn.setLayoutParams(new LayoutParams(iWidth, iHeight));
		return btn;
	}

	// private void generateTopButtons(LinearLayout layTopControls) {

	// final int iSmallButtonWidth = 40;
	// btnToday = createButton("回到今天", iTotalWidth - iSmallButtonWidth * 2,
	// android.view.ViewGroup.LayoutParams.WRAP_CONTENT);

	// monthTextView = new TextView(this);
	// monthTextView.setPadding(8, 8, 8, 8);
	// monthTextView.setText(mYear + "");
	// monthTextView.setWidth(80);
	//
	// yearTextView = new TextView(this);
	// yearTextView.setPadding(20, 8, 8, 8);
	// yearTextView.setText(format(mMonth + 1));
	// yearTextView.setWidth(80);

	// Button btnPrevMonth = new Button(this);
	// btnPrevMonth.setLayoutParams(new LayoutParams(iSmallButtonWidth,
	// android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
	// btnPrevMonth.setBackgroundResource(R.drawable.prev_month);
	//
	// Button btnNextMonth = new Button(this);
	// btnNextMonth.setLayoutParams(new LayoutParams(iSmallButtonWidth,
	// android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
	// btnNextMonth.setBackgroundResource(R.drawable.next_month);
	//
	// btnNextMonth.setOnClickListener(new Button.OnClickListener() {
	// @Override
	// public void onClick(View arg0) {
	// setNextMonthViewItem();
	// }
	// });
	//
	// btnPrevMonth.setOnClickListener(new Button.OnClickListener() {
	// @Override
	// public void onClick(View arg0) {
	// setPrevMonthViewItem();
	// }
	// });
	//
	// layTopControls.setGravity(Gravity.CENTER_HORIZONTAL);
	// layTopControls.addView(btnPrevMonth);
	// layTopControls.addView(monthTextView);
	// layTopControls.addView(yearTextView);
	// layTopControls.addView(btnNextMonth);
	// }

	private View generateContentView() {
		LinearLayout layMain = createLayout(LinearLayout.VERTICAL);
		layMain.setPadding(8, 8, 8, 8);
		LinearLayout layTopControls = createLayout(LinearLayout.HORIZONTAL);

		layContent = createLayout(LinearLayout.VERTICAL);
		layContent.setPadding(20, 0, 20, 0);
		// generateTopButtons(layTopControls);
		generateCalendar(layContent);
		layMain.addView(layTopControls);
		layMain.addView(layContent);

		// tv = new TextView(this);
		// tv.setPadding(20, 0, 20, 0);
		// layMain.addView(tv);
		return layMain;
	}

	private View generateCalendarRow() {
		LinearLayout layRow = createLayout(LinearLayout.HORIZONTAL);
		for (int iDay = 0; iDay < 7; iDay++) {
			DateWidgetDayCell dayCell = new DateWidgetDayCell(this, iDayCellSize, iDayCellSize);
			dayCell.setItemClick(mOnDayCellClick);
			days.add(dayCell);
			layRow.addView(dayCell);
		}
		return layRow;
	}

	private View generateCalendarHeader() {
		LinearLayout layRow = createLayout(LinearLayout.HORIZONTAL);
		for (int iDay = 0; iDay < 7; iDay++) {
			DateWidgetDayHeader day = new DateWidgetDayHeader(this, iDayCellSize, iDayHeaderHeight);
			final int iWeekDay = DayStyle.getWeekDay(iDay, iFirstDayOfWeek);
			day.setData(iWeekDay);
			layRow.addView(day);
		}
		return layRow;
	}

	private void generateCalendar(LinearLayout layContent) {
		layContent.addView(generateCalendarHeader());
		days.clear();
		for (int iRow = 0; iRow < 5; iRow++) {
			layContent.addView(generateCalendarRow());
		}
	}

	private Calendar getCalendarStartDate() {
		calToday.setTimeInMillis(System.currentTimeMillis());
		calToday.setFirstDayOfWeek(iFirstDayOfWeek);

		if (calSelected.getTimeInMillis() == 0) {
			calStartDate.setTimeInMillis(System.currentTimeMillis());
			calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
		} else {
			calStartDate.setTimeInMillis(calSelected.getTimeInMillis());
			calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
		}
		updateStartDateForMonth();

		return calStartDate;
	}

	private DateWidgetDayCell updateCalendar() {
		DateWidgetDayCell daySelected = null;
		boolean bSelected = false;
		final boolean bIsSelection = (calSelected.getTimeInMillis() != 0);
		final int iSelectedYear = calSelected.get(Calendar.YEAR);
		final int iSelectedMonth = calSelected.get(Calendar.MONTH);
		final int iSelectedDay = calSelected.get(Calendar.DAY_OF_MONTH);
		calCalendar.setTimeInMillis(calStartDate.getTimeInMillis());
		for (int i = 0; i < days.size(); i++) {
			final int iYear = calCalendar.get(Calendar.YEAR);
			final int iMonth = calCalendar.get(Calendar.MONTH);
			final int iDay = calCalendar.get(Calendar.DAY_OF_MONTH);
			final int iDayOfWeek = calCalendar.get(Calendar.DAY_OF_WEEK);
			DateWidgetDayCell dayCell = days.get(i);
			// check today
			boolean bToday = false;
			if (calToday.get(Calendar.YEAR) == iYear)
				if (calToday.get(Calendar.MONTH) == iMonth)
					if (calToday.get(Calendar.DAY_OF_MONTH) == iDay)
						bToday = true;

			boolean bTom = false;
			if (nextDate.get(Calendar.YEAR) == iYear)
				if (nextDate.get(Calendar.MONTH) == iMonth)
					if (nextDate.get(Calendar.DAY_OF_MONTH) == iDay)
						bTom = true;

			boolean bTomm = false;
			if (nnextDate.get(Calendar.YEAR) == iYear)
				if (nnextDate.get(Calendar.MONTH) == iMonth)
					if (nnextDate.get(Calendar.DAY_OF_MONTH) == iDay)
						bTomm = true;

			// check holiday
			boolean bHoliday = false;

			dayCell.setData(iYear, iMonth, iDay, bToday, bTom, bTomm, bHoliday, iMonthViewCurrentMonth,
					iDayOfWeek);
			dayCell.invalidate();

			boolean isClick = false;
			// TODO
			if ((iYear > calToday.get(Calendar.YEAR))) {
				isClick = true;
			} else if ((iYear >= calToday.get(Calendar.YEAR) && (iMonth > calToday.get(Calendar.MONTH)))) {
				isClick = true;
			} else if ((iYear >= calToday.get(Calendar.YEAR) && (iMonth >= calToday.get(Calendar.MONTH)) && (iDay >= calToday
					.get(Calendar.DAY_OF_MONTH)))) {
				isClick = true;
			}
			dayCell.setClick(isClick);

			bSelected = false;
			if (bIsSelection)
				if ((iSelectedDay == iDay) && (iSelectedMonth == iMonth) && (iSelectedYear == iYear)) {
					bSelected = true;
				}
			dayCell.setSelected(bSelected);
			if (bSelected)
				daySelected = dayCell;
			calCalendar.add(Calendar.DAY_OF_MONTH, 1);
		}
		layContent.invalidate();
		return daySelected;
	}

	private void updateStartDateForMonth() {
		iMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH);
		iMonthViewCurrentYear = calStartDate.get(Calendar.YEAR);
		calStartDate.set(Calendar.DAY_OF_MONTH, 1);
		UpdateCurrentMonthDisplay();
		// update days for week
		int iDay = 0;
		int iStartDay = iFirstDayOfWeek;
		if (iStartDay == Calendar.MONDAY) {
			iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
			if (iDay < 0)
				iDay = 6;
		}
		if (iStartDay == Calendar.SUNDAY) {
			iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
			if (iDay < 0)
				iDay = 6;
		}
		calStartDate.add(Calendar.DAY_OF_WEEK, -iDay);
	}

	private void UpdateCurrentMonthDisplay() {
		String s = calCalendar.get(Calendar.YEAR) + "/" + (calCalendar.get(Calendar.MONTH) + 1);// dateMonth.format(calCalendar.getTime());
		// btnToday.setText(s);
		mYear = calCalendar.get(Calendar.YEAR);
	}

	private void setPrevMonthViewItem() {
		iMonthViewCurrentMonth--;
		if (iMonthViewCurrentMonth == -1) {
			iMonthViewCurrentMonth = 11;
			iMonthViewCurrentYear--;
		}
		calStartDate.set(Calendar.DAY_OF_MONTH, 1);
		calStartDate.set(Calendar.MONTH, iMonthViewCurrentMonth);
		calStartDate.set(Calendar.YEAR, iMonthViewCurrentYear);
		updateDate();
		updateCenterTextView(iMonthViewCurrentMonth, iMonthViewCurrentYear);
	}

	private void setNextMonthViewItem() {
		iMonthViewCurrentMonth++;
		if (iMonthViewCurrentMonth == 12) {
			iMonthViewCurrentMonth = 0;
			iMonthViewCurrentYear++;
		}
		calStartDate.set(Calendar.DAY_OF_MONTH, 1);
		calStartDate.set(Calendar.MONTH, iMonthViewCurrentMonth);
		calStartDate.set(Calendar.YEAR, iMonthViewCurrentYear);
		updateDate();
		updateCenterTextView(iMonthViewCurrentMonth, iMonthViewCurrentYear);
	}

	private final DateWidgetDayCell.OnItemClick mOnDayCellClick = new DateWidgetDayCell.OnItemClick() {
		@Override
		public void OnClick(DateWidgetDayCell item) {
			calSelected.setTimeInMillis(item.getDate().getTimeInMillis());
			item.setSelected(true);
			updateCalendar();
			updateControlsState();
			Intent i = new Intent(CalendarActivity.this, ReservationActivity.class);
			i.putExtra("date", strDate);
			setResult(RESULT_OK, i);
			finish();

		}
	};

	/**
	 * 更新表头
	 * 
	 * @param iMonthViewCurrentMonth
	 * @param iMonthViewCurrentYear
	 */
	private void updateCenterTextView(int iMonthViewCurrentMonth, int iMonthViewCurrentYear) {
		// monthTextView.setText(iMonthViewCurrentYear + "");
		// yearTextView.setText(format(iMonthViewCurrentMonth + 1) + "");

		tvMonth.setText(format(iMonthViewCurrentMonth + 1) + "月");
		tvYear.setText(iMonthViewCurrentYear + "年");
	}

	private void updateDate() {
		updateStartDateForMonth();
		updateCalendar();
	}

	private void updateControlsState() {
		mYear = calSelected.get(Calendar.YEAR);
		mMonth = calSelected.get(Calendar.MONTH);
		mDay = calSelected.get(Calendar.DAY_OF_MONTH);
		// tv.setText("您选择的日期是："
		// + new StringBuilder().append(mYear).append("/").append(format(mMonth
		// + 1)).append("/")
		// .append(format(mDay)));

		Date date = calSelected.getTime();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		strDate = format.format(date);

		// tv.setText(strDate);

		// tv.setHorizontallyScrolling(true);

		updateCenterTextView(mMonth, mYear);
		// SharedPreferences mPerferences =
		// PreferenceManager.getDefaultSharedPreferences(this);
		// SharedPreferences.Editor mEditor = mPerferences.edit();
		// if (type == 0)
		// mEditor.putString("check_in", format(mMonth + 1) + "-" + format(mDay)
		// + "-" + mYear);
		// else if (type == 1)
		// mEditor.putString("check_out", format(mMonth + 1) + "-" +
		// format(mDay) + "-" + mYear);
		// mEditor.commit();
	}

	private String format(int x) {
		String s = "" + x;
		if (s.length() == 1)
			s = "0" + s;
		return s;
	}

}
